<template>
  <view class="main-view">
    <view class="top-view">
      <eui-card hPadding="20">
        <eui-text :value="getActivityName(mainData.c_pro_plan_id, mainData.c_pro_plan_name)" type="name2" title="促销活动" cWidth="width: 100%" />
        <eui-text :value="getDictName('促销发起方', mainData.c_owner)" type="name2" title="发起方" />
        <eui-text :value="getDictName('顾客类型', mainData.c_mem_type)" type="name2" title="顾客类型" />
        <eui-text :value="getName('rdsStores', mainData.c_store_id)" type="name2" title="机构" :valueStyle="valueStyle" cWidth="width: 100%" />
        <eui-text :value="getDictName('促销折让方式', mainData.c_pro_fall_type)" type="name2" title="库存折让方式" cWidth="width: 100%" />
        <eui-text :value="mainData.c_order_sda" type="date" title="订货起始日" cWidth="width: 100%" />
        <eui-text :value="mainData.c_order_eda" type="date" title="订货结束日" cWidth="width: 100%" />
        <eui-text :value="mainData.c_sale_sda" type="date" title="销售起始日" cWidth="width: 100%" />
        <eui-text :value="mainData.c_sale_eda" type="date" title="销售结束日" cWidth="width: 100%" />
        <eui-text v-if="showBtn" value="查看限制规则" type="link" title="" @click="openPopup" />
      </eui-card>
    </view>
    <view class="footer-view" :style="{ height: listHeight + 'rpx' }">
      <eui-paging ref="paging" v-model="listManager" :fixed="false" :refresher-enabled="false"
                  :default-page-size="10" :loading-more-enabled="true" :show-loading-more-when-reload="true">
        <view v-for="(item, index) in listManager" :key="index" class="item-view">
          <eui-text :value="index + 1 + '. [' + item.c_gcode + ']' + item.c_gname" type="name2"
                    title="" cWidth="width: 100%" />
          <eui-text v-model="item.c_barcode" type="name2" title="条码" />
          <eui-text :value="item.c_take_range_mname" type="name2" title="影响范围" />
          <eui-text :value="item.c_code_by_mname" type="name2" title="价格类型" />
          <eui-text :value="item.c_con_no" type="name2" title="合同编码" />
          <eui-text :value="item.c_take_method_mname" type="name2" title="损失处理方法" />
          <eui-text :value="item.c_rate_type_mname" type="name2" title="损失计算方法" />
          <eui-text :value="item.c_provider_mname" type="name2" title="供应商" cWidth="width: 100%" />
          <eui-text :value="item.c_price" :oldValue="item.c_price0" type="price2" title="促销售价" :valueStyle="showRightStyle" cWidth="width: 100%" />
          <eui-text :value="item.c_price_rate" :oldValue="item.c_price_rate0" type="price2" title="促销折扣(%)" :valueStyle="showRightStyle" cWidth="width: 100%" />
          <eui-text :value="item.c_mprice" :oldValue="item.c_mprice0" type="price2" title="促销会员价" :valueStyle="showRightStyle" cWidth="width: 100%" />
          <eui-text :value="item.c_mprice_rate" type="price2" title="会员价折扣(%)" :valueStyle="showRightStyle" cWidth="width: 100%" />
          <eui-text v-if="['1', '2', '3'].includes(item.c_con_type)" :value="item.c_take_rate" type="price2" :precision="4" title="促销进价" :valueStyle="showRightStyle" cWidth="width: 100%" />
          <eui-text v-else-if="['4', '5'].includes(item.c_con_type)" :value="item.c_take_rate" type="price2" title="促销扣率(%)" :valueStyle="showRightStyle" cWidth="width: 100%" />
        </view>
      </eui-paging>
    </view>
    <eui-popup ref="popup" background-color="#f8f8f8" type="bottom" :mask-click="true">
      <view class="popup-content">
        <view>
          <eui-segmented-control :current="current" :values="items" @clickItem="onClickItem"
                                 style-type="text" active-color="#01b0c6" bgColor="#888"></eui-segmented-control>
        </view>
        <template v-if="current === 0">
          <scroll-view v-if="timeList.length > 0" scroll-y="true"
                       style="width: 100%;height:400px;box-sizing: border-box;overflow-y: scroll;">
            <view v-for="(item, index) in timeList" :key="index">
              <view class="item-view">
                <eui-text v-if="item.targetDetail" :value="item.targetDetail" type="name2" :title="index + 1 + '. ' + '指定明细:'" cWidth="width: 100%;white-space: normal;overflow: visible;display: block;" />
                <eui-text v-else :value="item.c_day" type="name2" :title="index + 1 + '. ' + '日:'" cWidth="width: 100%" />
                <eui-text v-if="item.targetDetail" :value="item.c_day" type="name2" title="日" cWidth="width: 100%" />
                <eui-text :value="item.weeks_str" type="name2" title="星期" cWidth="width: 100%" />
                <eui-text :value="item.c_stime" type="name2" title="开始时间" />
                <eui-text :value="item.c_etime" type="name2" title="结束时间" />
                <eui-text v-if="item.c_price" :value="item.c_price" type="price2" title="促销售价" :valueStyle="showRightStyle" />
                <eui-text v-if="item.c_price_rate" :value="item.c_price_rate" type="price2" title="促销折扣(%)" :valueStyle="showRightStyle" />
                <eui-text v-if="item.c_mprice" :value="item.c_mprice" type="price2" title="促销会员价" :valueStyle="showRightStyle" />
                <eui-text v-if="item.c_mprice_rate" :value="item.c_mprice_rate" type="price2" title="会员价折扣(%)" :valueStyle="showRightStyle" />
                <eui-text :value="item.c_note" type="name2" title="备注" cWidth="width: 100%;white-space: normal;overflow: visible;display: block;" />
              </view>
            </view>
          </scroll-view>
          <view v-else class="temp-view">
            <text>未设置时段限制</text>
          </view>
        </template>
        <template v-else-if="current === 1">
          <scroll-view v-if="pointList.length > 0" scroll-y="true"
                       style="width: 100%;height:400px;box-sizing: border-box;overflow-y: scroll;">
            <view v-for="(item, index) in pointList" :key="index">
              <view class="item-view">
                <eui-text :value="item.targetDetail" type="name2" :title="index + 1 + '. ' + '指定明细:'" cWidth="width: 100%;white-space: normal;overflow: visible;display: block;" />
                <eui-text :value="item.c_min_score" type="price2" title="积分下限" :valueStyle="showRightStyle" />
                <eui-text :value="item.c_use_score" type="price2" title="使用积分" :valueStyle="showRightStyle" />
                <eui-text v-if="item.c_off_amt != null" :value="item.c_off_amt" type="price2" title="抵用金额" :valueStyle="showRightStyle" />
                <eui-text v-if="item.c_to_amt != null" :value="item.c_to_amt" type="price2" title="抵至金额" :valueStyle="showRightStyle" />
                <eui-text :value="item.note_str" type="name2" title="备注" cWidth="width: 100%;white-space: normal;overflow: visible;display: block;" />
              </view>
            </view>
          </scroll-view>
          <view v-else class="temp-view">
            <text>未设置积分抵扣</text>
          </view>
        </template>
        <template v-else-if="current === 2">
          <scroll-view v-if="limitList.length > 0" scroll-y="true"
                       style="width: 100%;height:400px;box-sizing: border-box;overflow-y: scroll;">
            <view v-for="(item, index) in limitList" :key="index">
              <view class="item-view">
                <eui-text :value="item.targetDetail" type="name2" :title="index + 1 + '. ' + '指定明细:'" cWidth="width: 100%;white-space: normal;overflow: visible;display: block;" />
                <eui-text :value="item.c_lmt_p_dim_mnama" type="name2" title="客户" />
                <eui-text :value="item.c_lmt_s_dim_mnama" type="name2" title="机构" />
                <eui-text :value="item.c_lmt_d_dim_mnama" type="name2" title="时间" />
                <eui-text :value="item.c_n_lmt" type="number3" title="限量" />
                <eui-text :value="item.note_str" type="name2" title="备注" cWidth="width: 100%;white-space: normal;overflow: visible;display: block;" />
              </view>
            </view>
          </scroll-view>
          <view v-else class="temp-view">
            <text>未设置限量规则</text>
          </view>
        </template>
      </view>
    </eui-popup>
  </view>
</template>

<script setup type="ts">
import { ref, reactive, onMounted, defineComponent, withDefaults, defineProps, watch } from 'vue';
import dayjs from 'dayjs';
import {useMainStore} from "@/store/modules/store";
import {useLoginStore} from "@/store/modules/useLoginStore";
import { validateStores } from '@/hooks/useValidateMethod';
import { getRdsUrl, rdsRequest } from '@/hooks/rdsServices';
import service from "@/common/service";
import {onLoad} from "@dcloudio/uni-app";
import Enjoy from "@/common/enjoy";
import { getDictSelectList, getDictList } from '../RdsViews/components/RelatedName.js';
import dateRangUtil from '../../common/dateRangUtil';
const mainStore = useMainStore();
const LoginStore = useLoginStore();
const rdsUrl = getRdsUrl();
const valueStyle = ref('white-space: nowrap;overflow: hidden;text-overflow: ellipsis;')
const showRightStyle = ref('text-align: right');

const title = ref('商品价格促销单');
const listHeight = ref(300);
const mainData = ref({});
const columnData = ref([]);
const listManager = ref([]);
const paging = ref(null);
let rdsDict = reactive([]);
let dictMap = reactive({});
let rdsStoresMap = reactive({}); //机构
let rdsWnosMap = reactive({}); //仓库
let rdsProvidersMap = reactive({}); //供应商
let rdsDepartsMap = reactive({}); //部门
let rdsGdsclassesMap = reactive({}); //品类
let timeList = ref([]); //时段限制
let pointList = ref([]); //积分抵扣
let limitList = ref([]); //限量规则
// 弹框
const popup = ref(null);
let showBtn = ref(false);
let items = ref(['时段限制', '积分抵扣', '限量规则']);
let current = ref(0);

const props = defineProps({
  data: {
    type: Object
  },
  windowWidth: {
    type: Number,
    default: 0,
  }
});

onMounted (async () => {
  await getListHeight();
  await getAllDicData();
  if (props.data.BillId) {
    await billQuery();
  }
});

// 获取列表高度
const getListHeight = async () => {
  await uni.getSystemInfo({
    success: function (res) { // res - 各种参数
      let info = uni.createSelectorQuery().select(".footer-view");
      info.boundingClientRect(function (data) { //data - 各种参数
        let info2 = uni.createSelectorQuery().select(".user-footer");
        info2.boundingClientRect(function (data2) { //data - 各种参数
          //获取列表高度
          let height = res.windowHeight - data.top - data2.height;
          //转换rpx
          listHeight.value = height / (res.windowWidth / 750) - 20;
        }).exec()
      }).exec()
    }
  });
};

// 获取字典数据
const getAllDicData = async () => {
  rdsDict = await service.getLocalStorage('rdsDict');
  dictMap = new Map();
  for (const item of rdsDict) {
    const key = item.c_class_name;
    const value = item.c_id;
    const name = item.c_name;
    if (!dictMap.has(key)) {
      dictMap.set(key, new Map());
    }
    dictMap.get(key).set(value, name);
  }
  rdsStoresMap = await service.getLocalStorage('rdsStores');
  rdsWnosMap = await service.getLocalStorage('rdsWnos');
  rdsProvidersMap = await service.getLocalStorage('rdsProviders');
  rdsDepartsMap = await service.getLocalStorage('rdsDeparts');
  rdsGdsclassesMap = await service.getLocalStorage('rdsGdsclasses');
}

// 字段翻译
const translateWeekdays = (weekdays, input) => {
  // 将字典转换为一个 ID 到名称的映射
  const idToNameMap = weekdays.reduce((map, item) => {
    map[item.c_id] = item.c_name;
    return map;
  }, {});
  // 将输入字符串中的每个字符映射到相应的星期名称
  const result = input.split('')
      .map(digit => idToNameMap[digit] || '') // 使用空字符串处理无效的字符
      .filter(name => name) // 去除无效的星期名称
      .join(','); // 使用逗号连接
  return result;
}

// 积分抵扣备注
const setProScoreNote = (record) => {
  let res = '';
  if (record["c_min_score"]) {
    res += `用户积分满[${record["c_min_score"]}],`

  }
  if (record["c_use_score"]) {
    res += `使用[${record["c_use_score"]}]积分,`
  }
  if (record["c_off_amt"] != null) {
    res += `可抵用[${record["c_off_amt"]}元]`
  }
  else if (record["c_to_amt"] != null) {
    res += `可抵至[${record["c_to_amt"]}元]`
  }
  return res;
}

// 限量规则备注
const setProLmtNote =(record) => {
  let res = '';
  if (record["c_lmt_p_dim"]) {
    switch (record["c_lmt_p_dim"]) {
      case '0':
        res += '所有客户累计'
        break;
      case '1':
        res += '每个客户'
        break;
    }

  }
  if (record["c_lmt_s_dim"]) {
    switch (record["c_lmt_s_dim"]) {
      case '0':
        res += '在当前活动的机构和渠道范围下'
        break;
      case '1':
        res += '每个机构'
        break;
      case '2':
        res += '每个渠道'
        break;
      case '3':
        res += '每个机构和渠道范围下'
        break;
    }
  }
  if (record["c_lmt_d_dim"]) {
    switch (record["c_lmt_d_dim"]) {
      case 'P':
        res += '活动期间内'
        break;
      case 'D':
        res += '每天'
        break;
      case 'W':
        res += '每周'
        break;
      case 'M':
        res += '每月'
        break;
      case 'Q':
        res += '每个季度'
        break;
      case 'Y':
        res += '每年'
        break;
      case 'E':
        res += '每次'
        break;
    }
  }
  if (record["c_n_lmt"]) {
    res += `限量${record["c_n_lmt"]}件`;
  }
  else {
    res += `不限量`;
  }
  return res;
}

// 指定明细
const getPropertyInfo = (value) => {
  let str = '';
  let data = columnData.value.find(x => x.c_gsort === value.c_gsort);
  if (data) {
    str = `[${data.c_gsort}]商品:[${data.c_gcode}],名称:[${data.c_gname}],促销方式:[${data.c_code_by}]${data.c_code_by_mname},条码:[${data.c_barcode}],供应商:${data.c_provider_mname},合同:[${data.c_con_no}]`;
  }
  return str;
}

// 获取单据详情信息
const billQuery = async () => {
  service.enjoyShowLoading("正在加载...")
  const req = {
    BillId: props.data.BillId,
  };
  const result = await rdsRequest(rdsUrl.bcApi, '商品价格促销单', 'EnjoyBillQuery', req, '201');
  if (result.ds.length > 0) {
    mainData.value = result.ds[0];
    let showList = result.ds1;
    showList.forEach(x => {
      x.c_provider_mname = getName('rdsProviders', x.c_provider);
      x.c_code_by_mname = getDictName('价格类型', x.c_code_by);
      x.c_take_method_mname = getDictName('损失承担方法', x.c_take_method);
      x.c_rate_type_mname = getDictName('损失计算方法', x.c_rate_type);
      x.c_take_range_mname = getDictName('促销进价影响范围', x.c_take_range);
    })
    columnData.value = showList;
    paging.value.setLocalPaging(showList);
    // 时段限制
    if (result.ds3 && result.ds3.length > 0) {
      timeList.value = result.ds3;
      timeList.value.forEach(x => {
        x.targetDetail = getPropertyInfo(x);
        let weeks = rdsDict.filter(x => x.c_class_name === '星期');
        x.weeks_str = translateWeekdays(weeks, x.c_week_day);
      })
    } else {
      timeList.value = result.ds6;
      timeList.value.forEach(x => {
        let weeks = rdsDict.filter(x => x.c_class_name === '星期');
        x.weeks_str = translateWeekdays(weeks, x.c_week_day);
      })
    }
    // 积分抵扣
    pointList.value = result.ds4;
    pointList.value.forEach(x => {
      x.note_str = setProScoreNote(x);
      x.targetDetail = getPropertyInfo(x);
    })
    // 限量规则
    limitList.value = result.ds5;
    limitList.value.forEach(x => {
      x.c_lmt_p_dim_mnama = getDictName('客户限量维度', x.c_lmt_p_dim);
      x.c_lmt_s_dim_mnama = getDictName('机构限量维度', x.c_lmt_s_dim);
      x.c_lmt_d_dim_mnama = getDictName('时间限量维度', x.c_lmt_d_dim);
      x.note_str = setProLmtNote(x);
      x.targetDetail = getPropertyInfo(x);
    })
    showBtn.value = timeList.value.length > 0 ||  pointList.value.length > 0 || limitList.value.length > 0;
  } else {
    uni.showToast({
      duration: 2000,
      icon: 'none',
      title: '未查询到数据',
      mask: true,
    });
  }
  service.enjoyHideLoading();
}

// 打开弹框
const openPopup = () => {
  popup.value.open();
}

// 关闭弹框
const closePopup = () => {
  popup.value.close();
}
const onClickItem = (e) => {
  if (current.value !== e.currentIndex) {
    current.value = e.currentIndex;
  }
}

const getName = (key, value) => {
  let list = [];
  if (!value) {
    return ''
  }
  value.split(',').map(item => {
    const flag = isEnglishLettersOnly(key)
    if (flag) {
      list.push("[" + item + "]" + getRelatedName(key, item) || '');
    } else {
      list.push("[" + item + "]" + key);
    }
  })
  return list.join(',');
}

const isEnglishLettersOnly = (str) => {
  // 正则表达式，匹配所有的英文字母
  const regex = /^[A-Za-z]+$/;
  return regex.test(str);
}

const getDictName = (key, value) => {
  const dictMap = rdsDict.find(x => x.c_class_name === key && x.c_id === value);
  return dictMap ? dictMap.c_name : ''
}

const getValueName = (key, value) => {
  const valueMap = dictMap.get(key);
  return valueMap ? valueMap.get(value) || '' : '';
}

const getRelatedName = (key, value) => {
  switch (key) {
    case 'rdsStores':
      return rdsStoresMap[value] ? rdsStoresMap[value] : '';
    case 'rdsWnos':
      return rdsWnosMap[value] ? rdsWnosMap[value] : '';
    case 'rdsProviders':
      return rdsProvidersMap[value] ? rdsProvidersMap[value] : '';
    case 'rdsDeparts':
      return rdsDepartsMap[value] ? rdsDepartsMap[value] : '';
    case 'rdsGdsclasses':
      return rdsGdsclassesMap[value] ? rdsGdsclassesMap[value] : '';
    default:
      return ''
  }
}

const getActivityName = (id = '', name = '') => {
  if (id) {
    return `[${id}]${name}`
  }
  return name
}

</script>

<style lang="scss" scoped>
@import '@/static/font/enjoyicon/iconfont.css';
@import '@/main.scss';

.content {
  padding: 0;
  display: flex;
}

.main-view {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.top-view {
  display: flex;
  width: 100%;
  height: auto;
  margin-bottom: 20rpx;
}

.footer-view {
  width: 100%;
  display: flex;
}

.navigation {
  flex: 2;
}

.footer {
  flex: 1;
  width: 100%;
  display: flex;
}

.m-list-top {
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  width: 100%;
  padding: 12rpx 12rpx 0 0;
  border-top: 1px solid #f5f5f5;
  font-size: 24rpx;
}

.table-text {
  font-size: 25rpx;
  margin: 10rpx;
}

.empty-view {
  width: 100%;
  height: 15rpx;
}

.item-view {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  align-items: center;
  row-gap: 8rpx;
  background: #ffffff;
  padding: 12rpx;
  border-bottom: 1px solid $uni-line-color;
}

.popup-content {
  align-items: center;
  justify-content: left;
  flex-direction: column;
  padding: 0;
  width: 100%;
  background-color: #f8f8f8;
}

.popup-height {
  width: 200px;
}

.popup-title {
  width: 100%;
  flex: 1;
  color: #666666;
  font-size: 0.8em;
  line-height: 2em;
  text-align: center;
  margin: 5px 0px 0px;
  border-bottom: 1px solid #cccccc;
}

.m-list-top-popup {
  display: grid;
  grid-template-columns: 51% 49%;
  padding: 8px 8px;
  border-bottom: 1px solid $uni-line-color;
  font-size: 12px;
}

.temp-view {
  width: 100%;
  height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 34rpx;
  color: #666666;
}

</style>
